import Request from '@/common/luch-request/index.js'
import configService from './config.service.js'
import {ACCESS_TOKEN} from '@/common/constant.js'
import { addressList } from '@/pages/weapp/user/address.js'

let apiUrl = configService.apiUrl;

const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync(ACCESS_TOKEN)
	} catch(e) {
		//TODO handle the exception
		console.log("getTokenStorage",token)
	}
	return token
}

const http = new Request()
http.setConfig((config) => { /* 设置全局配置 */
  config.baseUrl = apiUrl /* 根域名不同 */
  config.header = {
    ...config.header
  }
  return config
})

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  config.header = {
    ...config.header,
     'Authorization': getTokenStorage()
  }
  return config
})

http.interceptor.response(async (response) => { /* 请求之后拦截器 */
  if (response.data.code == 401) {
	  uni.showModal({
	  	title: '提示',
		content: '登录过期，请重新登录',
		success: (res) => {
			if (res.confirm) {
				getApp().globalData.clear = true;
				getApp().globalData.selected = null;
				addressList.splice(0)
				wx.switchTab({
					url: '/pages/weapp/user/user'
				})
		    }
		}
	  })
  }
  return response
})

export {
  http
}